<?php
require_once(JPATH_COMPONENT.DS.'dominio'.DS.'DTOFactory.php');

class SRGeocoder{
	var $_service_url=null;
	
	function SRGeocoder(){
		$this->_service_url = 'http://maps.google.com/maps/api/geocode/xml';
	}
	
//	public function geocode($address){
//		$address=preg_replace('/ /', '+', $address);
//		
//		$curl = curl_init($this->_service_url.'?address='.$address.'&sensor=false');
//		curl_setopt($curl, CURLOPT_HEADER, false); 
//       	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//       	$curl_response = curl_exec($curl);
//       	curl_close($curl);
//
//       	$xml = new SimpleXMLElement($curl_response);
//       	$xmlCoords=$xml->result[0]->geometry[0]->location[0];
//       	return DTOFactory::getInstance()->getDTOCoordinatesFromXML($xmlCoords);
//	}
	
	public function reverseGeocode($latLng){
		$address=preg_replace('/ /', '+', $latLng);
		
		$curl = curl_init($this->_service_url.'?latlng='.$latLng.'&sensor=false');
		curl_setopt($curl, CURLOPT_HEADER, false); 
       	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
       	$curl_response = curl_exec($curl);
       	curl_close($curl);

       	return new SimpleXMLElement($curl_response);
	}
	
	public function getDTOAreaAdmin ($xml){
		$dtoAreaAdmin=DTOFactory::getInstance()->createDTOAreaAdministrativa();
		$dtoPais=DTOFactory::getInstance()->createDTOPais();
		foreach ($xml->result->address_component as $addr_comp){
			foreach ($addr_comp->type as $type){
				if($type=="administrative_area_level_1"){
					$dtoAreaAdmin->setNameArea((string) $addr_comp->long_name);
				}
				if($type=="country"){
					$dtoPais->setNamePais((string) $addr_comp->long_name);
				}
			}
		}
		$dtoAreaAdmin->setPais($dtoPais);
		return $dtoAreaAdmin;
	}
		
}
?>